package com.atguigu.yygh.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/3/18 0:15
 */
//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 白名单路径直接放行
        if (antPathMatcher.match("/admin/user/**", path)){
            return chain.filter(exchange);
        }else {
            ServerHttpResponse response = exchange.getResponse();
            // 其他路径需要验证权限
            List<String> tokenList = request.getHeaders().get("X-Token");
            if (tokenList==null || tokenList.isEmpty()){
                return out(response);
            }

        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response){
        JSONObject msg = new JSONObject();
        msg.put("success", false);
        msg.put("data", "鉴权失败，请提供正确的token");
        msg.put("code", 28001);
        byte[] bytes = msg.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(dataBuffer));
    }
}
